package logic

import (
	"context"
	"github.com/pkg/errors"
	"zg2_zy/zy6_company/companyRpc/company"
	"zg2_zy/zy6_company/companyRpc/internal/svc"
	"zg2_zy/zy6_company/companyRpc/models"
	"zg2_zy/zy6_company/companyRpc/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePwdLogic {
	return &UpdatePwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePwdLogic) UpdatePwd(in *company.UpdatePwdRequest) (*company.UpdatePwdResponse, error) {
	// todo: add your logic here and delete this line

	var ur models.User
	ur.ID = uint(in.UserId)

	models.DB.Where("id=?", in.UserId).Find(&ur)
	if pkg.Md5(in.NewPwd) == "" || pkg.Md5(in.NewPwd) == ur.Password {
		return nil, errors.New("<密码格式不正确或与原密码一致>")
	}

	if in.NewPwd != in.SurePwd {
		return nil, errors.New("<两次密码不一致>")
	}

	ur.Password = pkg.Md5(in.NewPwd)
	models.DB.Updates(&ur)

	return &company.UpdatePwdResponse{
		UserId: int64(ur.ID),
	}, nil
}
